<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="物料大类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionBroad">
              <a-select
                v-model="model.provisionBroad"
                :disabled="companNameFlag"
                placeholder="请选择物料大类"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="handleChange"
                :getPopupContainer="(triggerNode)=>{ return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in provisionBroadList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="物料小类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="provisionSmall">
              <a-select
                v-model="model.provisionSmall"
                :disabled="companNameFlag"
                placeholder="请选择物料小类"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="provisionSmallChange"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in provisionSmallList" :key="item.id" :value="item.id">{{item.categoryName}}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="物料编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialBillId">
              <a-input disabled v-model="model.materialBillId" placeholder="请输入物料编号"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="物料名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="materialName">
              <select-material-input v-model="model.materialName" :disabled="companNameFlag" :materialFlag="true" :materialSmall="model.provisionSmall" @back="materialNameBack"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="规格型号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="specification">
              <a-input disabled v-model="model.specification" placeholder="请输入规格型号"  ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="unit">
              <j-dict-select-tag
                type="list"
                v-model="model.unit"
                placeholder="请选择单位"
                dictCode="unit_type"
                disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="品牌" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="brand">
              <a-input v-model="model.brand" placeholder="请输入品牌" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="供应商" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companName">
              <select-customer-input :disabled="companNameFlag" placeholder="请选择供应商名称" commercialType="2" v-model="model.companName"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="purchaseFlag">
            <a-form-model-item label="领用数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="purchaseNum">
              <a-input-number
                disabled
                :min="0"
                v-model="model.purchaseNum"
                placeholder="请输入领用数量"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12" v-if="purchaseFlag">
            <a-form-model-item label="累计已出库数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryAmount">
              <a-input-number
                disabled
                :min="0"
                v-model="model.deliveryAmount"
                placeholder="请输入累计已出库数量"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="出库仓库" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="storehouseId">
              <a-select
                v-model="model.storehouseId"
                :disabled="formDisabled"
                placeholder="请选择出库仓库"
                :showSearch="true"
                :allowClear="true"
                :filterOption="filterOption"
                @change="storeChange"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in foldWarehouseList" :key="item.id" :value="item.id">{{ item.categoryName }}</a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="库存数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="warehouseNum">
              <a-input-number disabled v-model="model.warehouseNum" placeholder="请输入库存数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item :label="deliveryNumLabel" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deliveryNum">
              <a-input-number :disabled="formDisabled" @change="deliveryNumChange" :max="99999999" :min="0"  v-model="model.deliveryNum" placeholder="请输入出库数量" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="remark">
              <a-textarea :disabled="formDisabled" :max-length="500" v-model="model.remark" rows="4" placeholder="请输入备注"/>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import SelectMaterialInput from '@/views/scy/components/SelectMaterialInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  export default {
    name: 'ErpPurchaseWarehouseDeliveryDetailForm',
    components: {
      SelectMaterialInput,
      SelectCustomerInput
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      storer: {
        type: String,
        default: ''
      },
      deliveryType: {
        type: String,
        default: ''
      }
    },
    data () {
      return {
        flag: false,
        model:{
          warehouseNum: null
        },
        labelCol: {},
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          provisionBroad: [
              { required: true, message: '请选择物料大类!', trigger: 'blur'},
          ],
          provisionSmall: [
              { required: true, message: '请选择物料小类!', trigger: 'blur'},
          ],
          materialName: [
              { required: true, message: '请选择物料名称!', trigger: 'change'},
          ],
          storehouseId: [
              { required: true, message: '请选择出库仓库!', trigger: 'blur'},
          ],
          deliveryNum: [
              { required: true, message: '请输入出库数量!', trigger: 'blur',type: 'number'},
              { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
          ],
          warehouseNum: [
              { pattern: /^[0-9]*[1-9][0-9]*$/, message: '库存数量不足，无法出库!' }
          ],
          purchaseNum: [
              { required: true, message: '请输入领用数量!', trigger: 'blur', type: 'number' },
              { pattern: /^[0-9]*[1-9][0-9]*$/, message: '请输入正整数!' }
          ],
          deliveryAmount: [
              { required: true, message: '请输入累计已出库数量!', trigger: 'blur', type: 'number' },
              { pattern: /^[0-9]\d*$/, message: '请输出整数!' }
          ]
        },
        url: {
          queryProvisionBroadList: "/api/erp/purchase/material/erpMaterialCategory/queryAllParent",
          queryProvisionSmallList: "/api/erp/purchase/material/erpMaterialCategory/queryChildrenByParentId",
          queryByStorehouseManager: '/api/erp/purchase/storehouse/erpStorehouseBase/queryByStorehouseManager',
          queryByStorehouseId: "/api/erp/purchase/storehouse/erpPurchaseWarehouse/queryByStorehouseIdAndMaterialName"
        },
        provisionBroadList: [],
        provisionSmallList: [],
        foldWarehouseList: [],
        purchaseFlag: false,
        companNameFlag: false,
        deliveryNumLabel: ''
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    watch: {
      storer: {
        handler (val) {
          if (val) {
            this.handleChangeFoldApplicant(val)
          }
        },
        immediate: true
      },
      deliveryType: {
        handler (val) {
          if (val) {
            this.handleChangeDeliveryType(val)
          }
        },
        immediate: true
      }
    },
    created () {
       //备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
    },
    methods: {
      deliveryNumChange(val){
        if(!this.model.warehouseNum || this.model.warehouseNum == 0){
          this.model.deliveryNum = null
          return
        }
        if(val > this.model.warehouseNum){
          this.$message.warning('出库数量不能大于库存数量')
          this.model.deliveryNum = null
          return
        }
      },
      storeChange(val){
        if(val){
          const that = this
          if(this.model.materialName){
            getAction(this.url.queryByStorehouseId,{ storehouseId: val, materialName: this.model.materialName}).then(res => {
              console.log(res);
              if(res.success){
                that.$set(that.model, 'warehouseNum', res.result ? res.result.amount : 0)
              }
            })
          } else {
            this.model.warehouseNum = null
          }
        } else {
            this.model.warehouseNum = null
        }
      },
      add () {
        this.edit(this.modelDefault);
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.findProvisionBroadList()
        this.model = Object.assign({}, record);
        this.provisionSmallList = []
        if (!!this.model.provisionBroad) {
          this.findProvisionSmallList(this.model.provisionBroad)
        }
        this.visible = true;
      },
      handleChangeFoldApplicant(v, num = 0) {
        const that = this
        getAction(this.url.queryByStorehouseManager, { storehouseManager: v }).then((res) => {
          if (res.success) {
            that.foldWarehouseList = []
            res.result.forEach((res) => {
              that.foldWarehouseList.push({ 'id': res.id, 'categoryName': res.storehouseName })
            })
            let storehouseFlag = that.foldWarehouseList.some(item => item.id == this.model.storehouseId)
            if(!storehouseFlag) {
              this.$set(this.model, 'storehouseId', undefined)
            }
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },
      findProvisionBroadList() {
        const that = this
        that.provisionBroadList = []
        getAction(this.url.queryProvisionBroadList).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionBroadList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      findProvisionSmallList(value) {
        const that = this
        const parentId = value
        getAction(this.url.queryProvisionSmallList, { parentId }).then(res => {
          if (res.success) {
            res.result.forEach((res) => {
              that.provisionSmallList.push({ 'id':res.id, 'categoryName':res.categoryName })
            })
          } else {
            that.$message.warning(res.message)
          }
        })
      },
      handleChange(value) {
        this.provisionSmallChange()
        this.provisionSmallList = []
        this.$set(this.model, 'provisionSmall', undefined);
        this.$refs["form"].clearValidate('provisionSmall');
        if (!!value) {
          this.findProvisionSmallList(value)
        }
      },
      materialNameBack(data) {
        const material = data[0]
        this.$set(this.model, 'materialBillId', material.materialBill)//物料编码
        this.$set(this.model, 'brand', material.brand)//品牌
        this.$set(this.model, 'specification', material.specification)//规格型号
        this.$set(this.model, 'unit', material.unit)//单位
        this.$set(this.model, 'companName', null)//供应商
        this.$set(this.model, 'deliveryNum', null)//出库数量
        if(this.model.storehouseId){
          getAction(this.url.queryByStorehouseId,{ storehouseId: this.model.storehouseId, materialName: material.id}).then(res => {
            if(res.success){
              this.model.warehouseNum = res.result?res.result.amount:0
            }
          })
        } else {
          this.model.warehouseNum = null
        }
      },
      provisionSmallChange() {
        this.$set(this.model, 'materialName', null)//物料名称
        this.$set(this.model, 'materialBillId', null)//物料编码
        this.$set(this.model, 'brand', null)//品牌
        this.$set(this.model, 'specification', null)//规格型号
        this.$set(this.model, 'unit', null)//单位
        this.$set(this.model, 'companName', null)//供应商
        this.$set(this.model, 'deliveryNum', null)//出库数量
      },
      submitForm () {
        //合同类 或 非合同类
        if(!!this.model.deliveryNum && this.deliveryType == 5) {
          let num = this.model.purchaseNum - this.model.deliveryAmount
          if(num < this.model.deliveryNum) {
            this.$message.warning('该类别本次出库数量（' + this.model.deliveryNum + '）不能大于领用数量（' + num + '）！');
            return
          }
        }
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.$emit('ok', this.model, this.flag);
          }
        })
      },
      handleChangeDeliveryType(data) {
        if(data == 5) {
          this.companNameFlag = true
          this.purchaseFlag = true
          this.deliveryNumLabel = '本次出库数量'
        } else {
          this.companNameFlag = false
          this.purchaseFlag = false
          this.deliveryNumLabel = '出库数量'
        }
      }
    }
  }
</script>
